﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Contabilidade;

namespace Contab
{
	public partial class TaxaForm : Form
	{
		public TaxaForm()
		{
			InitializeComponent();
			NomeTextBox.Focus();
		}

		private void TaxaForm_Load(object sender, EventArgs e)
		{
			LoadGrid(); 
		}

		private void LoadGrid()
		{
			TaxaController taxaController = new TaxaController();
			TaxaDataGridView.DataSource = taxaController.FetchAll();
			TaxaDataGridView.ClearSelection();
			NomeTextBox.Focus();
		}

		private void SaveButton_Click(object sender, EventArgs e)
		{
			Contab.Business.Library.Taxa taxa = new Contab.Business.Library.Taxa();
			long idTaxa;

			if(long.TryParse(IDTaxaTextBox.Text, out idTaxa))
				taxa.IDTaxa = idTaxa;

			taxa.Nome = NomeTextBox.Text;

			float valor;
			if (float.TryParse(ValorTextBox.Text, out valor))
				taxa.Valor = valor;

			taxa.Save();

			if(taxa.BrokenRulesCollection.Count > 0)
				MessageBox.Show(taxa.BrokenRulesCollection.ToString());

			Limpar();
			LoadGrid();
		}

		private void TaxaDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			Taxa taxa = (Taxa)((DataGridView)sender).SelectedRows[0].DataBoundItem;
			IDTaxaTextBox.Text = taxa.IDTaxa.ToString();
			NomeTextBox.Text = taxa.Nome;

			if (taxa.Valor.HasValue)
				ValorTextBox.Text = taxa.Valor.Value.ToString();
			else
				ValorTextBox.Text = String.Empty;

			ExcluirButton.Enabled = true;
		}

		private void ExcluirButton_Click(object sender, EventArgs e)
		{
			Taxa.Delete(IDTaxaTextBox.Text);
			ExcluirButton.Enabled = false;
			LoadGrid();
		}

		private void CancelarButton_Click(object sender, EventArgs e)
		{
			Limpar();
			ExcluirButton.Enabled = false;
		}

		private void Limpar()
		{
			IDTaxaTextBox.Text = String.Empty;
			NomeTextBox.Text = String.Empty;
			ValorTextBox.Text = String.Empty;
		}
	}
}
